@file:OptIn(ExperimentalUnitApi::class, ExperimentalAnimationApi::class,
    ExperimentalComposeUiApi::class
)

package toy.keli.edic.ui

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Rect
import android.os.Process
import android.util.DisplayMetrics
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewTreeObserver
import android.view.WindowManager
import androidx.activity.ComponentActivity.WINDOW_SERVICE
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.material.rememberScaffoldState
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.ExperimentalUnitApi
import androidx.compose.ui.viewinterop.AndroidView
import androidx.drawerlayout.widget.DrawerLayout
import androidx.navigation.compose.rememberNavController
import toy.keli.edic.R
import toy.keli.edic.data.config.MenuConf
import toy.keli.edic.ui.main.MainScreen
import toy.keli.edic.ui.main.components.BottomNavigationBar
import toy.keli.edic.ui.main.components.Confirm
import toy.keli.edic.ui.main.components.PrivacyPolicy
import toy.keli.edic.util.ActivityRun
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import toy.keli.edic.data.model.Article
import toy.keli.edic.data.plug.CategoryTree
import toy.keli.edic.ui.main.extend.bgRun

@Composable
fun bindkeyBoradEvent(onBoradChange: (isOpen:Boolean)->Unit={ ActivityRun.onKeyBoardStatusChange(it)},child: @Composable ()->Unit={}){
    val rootView = LocalView.current.rootView // 获取根视图
    var isKeyboardVisible by remember { mutableStateOf(false) }
    DisposableEffect(rootView) {
        val listener = ViewTreeObserver.OnGlobalLayoutListener {
            val r = Rect()
            rootView.getWindowVisibleDisplayFrame(r)
            //屏幕显示高度
            val outMetrics = DisplayMetrics()
            (rootView.context
                .getSystemService(WINDOW_SERVICE) as WindowManager).defaultDisplay.getMetrics(
                outMetrics
            )
            val heightDiff = outMetrics.heightPixels - (r.bottom - r.top)
            val navigationBarHeight: Int = 50;//view.context.navigationBarHeight
            val isOpen: Boolean =  (heightDiff > navigationBarHeight)
            if(isKeyboardVisible != isOpen){
                onBoradChange(isOpen)
                isKeyboardVisible = isOpen
            }
        }

        rootView.viewTreeObserver.addOnGlobalLayoutListener(listener)
        // 组件销毁时移除监听器
        onDispose {
            rootView.viewTreeObserver.removeOnGlobalLayoutListener(listener)
        }
    }
    child()
}

@Composable
fun Main(){
    //Android判断程序是否第一次启动   https://www.jb51.net/article/109558.htm
    val setting: SharedPreferences = ActivityRun.context.getSharedPreferences("toy.keli.edic", 0)
    val user_first = setting.getBoolean("FIRST", true)
    if (user_first) { // 第一次则跳转到欢迎页面
        ActivityRun.onBackPressed { false }
        PrivacyPolicy{
            setting.edit().putBoolean("FIRST", false).commit()
            bgRun {
                CategoryTree.rsyncDataPromPathAssets()
            }
            ActivityRun.restart()
        }
        return
    }

    val mType = MenuConf.type()
    bindkeyBoradEvent()
    when (mType.value) {
        MenuConf.right ->
            RootContent()

        MenuConf.bottom -> {
            MainContent()
        }
    }

}
@OptIn(InternalCoroutinesApi::class)
@SuppressLint("ClickableViewAccessibility", "InflateParams")
@Composable
@Preview
fun RootContent() {
    val navController = rememberNavController()
    val scaffoldState = rememberScaffoldState()
     AndroidView(factory = {
            //加载AndroidView布局。
            LayoutInflater.from(it).inflate(R.layout.activity_main, null)
        }) { it ->
            val drawerLayout: DrawerLayout = it.findViewById(R.id.content_drawer)
            val left: View = it.findViewById(R.id.main_left)
            //drawerLayout.openDrawer(Gravity.RIGHT)

            drawerLayout.setDrawerListener(object : DrawerLayout.DrawerListener{
                override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
                }

                override fun onDrawerOpened(drawerView: View) {
                    if (drawerView == left) {
                        drawerLayout.closeDrawer(Gravity.LEFT)
                        (ActivityRun.context as Activity).onBackPressed()
                    }
                }

                override fun onDrawerClosed(drawerView: View) {

                }

                override fun onDrawerStateChanged(newState: Int) {
//                        if(newState == )
                }
            })
            val ct: ComposeView = it.findViewById(R.id.conten_parent)
            val mu: ComposeView = it.findViewById(R.id.right_menu)
            ct.setContent {
                MainScreen(
                    navController = navController,
                    scaffoldState = scaffoldState,
                )
            }
            mu.setContent {
                BottomNavigationBar(
                    navController
                ) {
                    navController.navigate(it.route) {
                        launchSingleTop = true
                        popUpTo(navController.graph.startDestinationId)
                    }
                    drawerLayout.closeDrawers()
                }
            }

    }
}

@Composable
fun MainContent(){
    val navController = rememberNavController()
    val scaffoldState = rememberScaffoldState()
    Scaffold(
        bottomBar = {
            BottomNavigationBar(
                navController
            ) {
                navController.navigate(it.route) {
                    popUpTo(navController.graph.startDestinationId)
                    launchSingleTop = true
                }
            }
        }
    ) {
        Box(
            modifier = Modifier.padding(
                bottom = it.calculateBottomPadding()
            )
        ) {
            MainScreen(
                navController = navController,
                scaffoldState = scaffoldState,
            )
        }
    }

}